<?php
namespace jy_creditshop\order;
defined('BY_JYA') or exit('error');
/*
	配送费
*/
class dispatch extends \plugin{
	public function get_freight($goods_list,$pcd='',$throw_error=false,$showbaoyou=false){
		if(!$goods_list){
			return 0;
		}
		$this->throw_error=$throw_error;
		$total_price=0;
		$goods_total_price=0;
		$baoyoufee=0;
		$saleset=$this->plugin_setting('saleset');
		$newlist=array();
		foreach($goods_list as $goods){
			$default_template_id=pdo_getcolumn('jy_weishop_dispatch',array('uniacid'=>$_SESSION['uniacid'],'isdefault'=>1),'id');
			$dispatch=pdo_get('jy_weishop_goods_dispatch',array('goodsid'=>$goods['goodsid']));
			$goods_total_price+=1*$goods['money'];
			if($goods['dispatchtype']==1){
				//统一运费
				$total_price+=$goods['dispatch']*1;
			}elseif($goods['dispatchid']){
				$newlist[$goods['dispatchid']][]=$goods;
			}else{
				$newlist[$default_template_id][]=$goods;
			}
		}
		if($newlist){			
			foreach($newlist as $template_id=>$item){
				$total_weight=0;
				$total_num=0;
				foreach($item as $gv){
					//$goods['price']=$this->pdo_getcolumn('goods',array('id'=>$goods['goodsid']),'price');
					$total_num+=$gv['total'];
					$total_weight+=$gv['total']*$gv['weight'];
				}
				if($total_num || $total_weight){
					$get_dispatch_price=$this->get_dispatch_price($pcd,$template_id,$total_weight,$total_num);				
					$total_price+=$get_dispatch_price['fee'];
					$outarea=$get_dispatch_price['outarea'];
				}
			}
		}
		if($saleset['baoyou_status'] && $goods_total_price>=$saleset['baoyou_man']){
			//满额包邮！
			if($showbaoyou){
				return array('fee'=>0,'outarea'=>$outarea,'addbaoyoufee'=>$total_price,'isonebaoyou'=>$isbaoyou);
			}else{
				return 0;
			}
		}
		if($showbaoyou){
				return array('fee'=>$total_price,'outarea'=>$outarea,'addbaoyoufee'=>0,'isonebaoyou'=>$isbaoyou);
		}else{
				return $total_price;
		}
	}
	public function get_dispatch_price($pcd='',$template_id,$weight,$total){
		$dispatch=pdo_get('jy_weishop_dispatch',array('id'=>$template_id));
		if($dispatch['isdispatcharea']==0 && $pcd){
			//不配送区域
			$nodispatchareas=json_decode($dispatch['nodispatchareas'],true);
			if($this->check_pcd($pcd,$nodispatchareas)){
				$outarea=1;
				if($this->throw_error){
					throw new \Exception('您的收货地址不在商品配送范围！');
				}
				exi('您的收货地址不在商品配送范围！','error');
			}
		}
		if($dispatch['isdispatcharea']==1 && $pcd){
			//只配送区域
			$onlydispatchareas=json_decode($dispatch['onlydispatchareas'],true);
			if(!$this->check_pcd($pcd,$onlydispatchareas)){
				$outarea=1;
				if($this->throw_error){
					throw new \Exception('您的收货地址不在商品配送范围！');
				}
				exi('您的收货地址不在商品配送范围！','error');
			}
		}
		if($dispatch['type']==0){
			//按重量计费
			$count=$weight;
		}else{
			$count=$total;
		}
		$price=0;
		if($dispatch['isdispatcharea']<=1 || !$pcd){
			//统一计费
			$price=$dispatch['shouprice'];
			if($dispatch['xuweight'] && $dispatch['xuprice'] && $count>$dispatch['shouweight']){
				$price+=ceil(($count-$dispatch['shouweight'])/$dispatch['xuweight'])*$dispatch['xuprice'];
			}
			$DATA=ijson_encode($dispatch);
		}else{			
			//自定义配送区域，寻找匹配的配送区域设置
			$areas=json_decode($dispatch['areas'],true);
			if($areas){
				foreach($areas as $av){
					$av['area']=$av['area']?json_decode($av['area'],true):array();
					if($this->check_pcd($pcd,$av['area'])){
						//区域命中
						$isarea=true;
						$price=$av['shouprice'];
						if($av['xu'] && $av['xuprice'] && $count>$av['shou']){
							$price+=ceil(($count-$av['shou'])/$av['xu'])*$av['xuprice'];
						}
						break;
					}
				}
				$outarea=$isarea?0:1;
			}
		}
		return array('fee'=>$price,'outarea'=>$outarea);
	}
	public function get_peisong($address='',$storeid=0,$addressid=0,$order_total_price=0){
		$city_express=$this->plugin_setting('citypeisong');
		$city_express['iscity']=true;
		if($addressid){
			$addressinfo=pdo_get('core_address', array('id' => $addressid, 'uniacid' => $_SESSION['uniacid']));
			$addressinfo['pcd']=json_decode($addressinfo['pcd'],true);
			if($addressinfo['pcd']['city']!=$city_express['pcd']['city']){
				$city_express['iscity']=false;
			}
			if($addressinfo['lat_lng']){
				$addressinfo['lat_lng']=json_decode($addressinfo['lat_lng'],true);
				$city_express_data = $this->get_peisong_fee($city_express, $addressinfo['lat_lng']['lng'], $addressinfo['lat_lng']['lat'],$order_total_price);
				return $city_express_data;
			}
		}
		$city_express_data = array('state' => 0, 'enabled' => 0, 'fee' => 0, 'is_dispatch' => $city_express['is_dispatch']);
		if ($city_express_data['enabled']!=1) {
			$city_express_data['enabled'] = 1;
			$city_express_data['is_sum'] = $city_express['is_sum'];
			if (!empty($address)) {
				$goodslat_leng=$city_express['lat_lng'];
				if($storeid){
					$goodslat_leng=pdo_getcolumn('jy_weishop_store',array('id'=>$storeid),'lat_lng');
					$city_express['lat_lng']=$goodslat_leng?:$city_express['lat_lng'];
				}
				$data = cfc('tools')->getgeocode($address, $city_express['geo_key']);
				if ($data['status'] == 1 && 0 < $data['count']) {
					$location = explode(',', $data['geocodes'][0]['location']);
					if($city_express['pcd']['city']!=$data['geocodes'][0]['city']){
						$city_express['iscity']=false;
					}
					if($addressid){
						$update=array(
							'lat_lng'=>ijson_encode(array('lat'=>$location[1],'lng'=>$location[0])),
							'area_code'=>$data['geocodes'][0]['citycode'],
						);
						pdo_update('core_address', $update, array('id' => $addressid, 'uniacid' => $_SESSION['uniacid']));
					}
					$city_express_data = $this->get_peisong_fee($city_express, $location[0], $location[1],$order_total_price);
				}else{
					$city_express_data['is_dispatch']=1;
				}
			}else{
				//没收货地址情况
				$city_express_data = $this->get_peisong_fee($city_express, '', '',$order_total_price);
			}
		}
		
		return $city_express_data;
	}
	public function get_peisong_fee($city_express, $lng, $lat,$order_total_price=0){
		$city_express_data = array('state' => 0, 'enabled' => 1, 'fee' => 0, 'is_sum' => $city_express['is_sum'], 'is_dispatch' => 0);
		if($city_express['lat_lng']){
			$distance = cfc('tools')->getdistance($city_express['lat_lng']['lat'], $city_express['lat_lng']['lng'], $lat, $lng);
		}else{
			$distance = 0;
		}
		$city_express_data['juli']=$distance/1000;
		if ($city_express['iscity']) {
			$city_express_data['state'] = 1;
			if ($distance <= $city_express['start_km'] * 1000) {
				$city_express_data['fee'] = round($city_express['start_fee'], 2);
			}

			if ($city_express['start_km'] * 1000 < $distance && $distance <= $city_express['start_km'] * 1000 + $city_express['pre_km'] * 1000) {
				$km = $distance - intval($city_express['start_km'] * 1000);
				$city_express_data['fee'] = round($city_express['start_fee'] + $city_express['pre_km_fee'] * ceil($km / 1000), 2);
			}

			if ($city_express['fixed_km'] * 1000 <= $distance) {
				$city_express_data['fee'] = round($city_express['fixed_fee'], 2);
			}
			if($city_express['man_fee'] && $order_total_price>=$city_express['man_fee']){
				//满额免配送！
				$city_express_data['addbaoyoufee']=$city_express_data['fee'];
				$city_express_data['fee']=0;
			}
			$city_express_data['iscity']=1;
		}elseif($city_express['is_dispatch']==1){//超出同城,使用快递方式
			$city_express_data['is_dispatch']=1;
		}else{//超出同城,不使用快递方式,不配送
			$city_express_data['iscity']=0;
		}
		$data=ijson_encode($city_express_data);
		return $city_express_data;
	}
	public function check_pcd($pcd='',$area){
		//检查行政区划是否存在于区域数组
		//如果没有传地址，就默认成功
		if(!$pcd){
			return true;
		}
		if(!$area[$pcd['province']]){
			return false;
		}
		if($area[$pcd['province']]==true){
			return true;
		}
		if(!$area[$pcd['province']][$pcd['city']]){
			return false;
		}
		if($area[$pcd['province']][$pcd['city']]==true){
			return true;
		}
		if(!$area[$pcd['province']][$pcd['city']][$pcd['district']]){
			return false;
		}
		return true;
	}
}